package pl.edu.uj.tcs.blef.protocol;

import java.io.PrintWriter;
import java.net.Socket;

import pl.edu.uj.tcs.blef.server.Client;
import pl.edu.uj.tcs.blef.server.Table;

public class AcceptRequestHandler extends AbstractTableHandler {

	public AcceptRequestHandler(Table table) {
		super(table);
	}

	@Override
	public void handle(Request request, Socket socket) {
		System.out.println("Handling " + request.message + " request from " + socket.getInetAddress().getHostAddress());
		AcceptRequest ctr = (AcceptRequest)request;
		if(!table.isOperator(socket)) {
			System.out.println("Unauthorized operator request from socket: " + socket.getInetAddress().getHostAddress());
			try {
				Request r = new UnknownRequestErrorFactory().build(null, new NullRequestHandler());
				r.send(new PrintWriter(socket.getOutputStream()));
			} catch (Exception e){}
		} else {
			if(!table.getIncomingPlayers().contains(new Client(ctr.getPlayerNick(), socket, 1))){
				String[] param = new String[1]; param[0] = ctr.getPlayerNick();
				try {
					Request r = new NoAwaitingPlayerErrorFactory().build(param, new NullRequestHandler());
					r.send(new PrintWriter(socket.getOutputStream()));
				} catch (Exception e){}
			} else {
				if(ctr.getCardAmount() <= 0 || ctr.getCardAmount() > 5){
					try {
						Request r = new InvalidParametersErrorFactory().build(null, new NullRequestHandler());
						r.send(new PrintWriter(socket.getOutputStream()));
					} catch (Exception e){}
				} else {
					Client client = null;
					for(Client c: table.getIncomingPlayers()){
						if(c.getNick().equals(ctr.getPlayerNick())) client = c;
					}
					
					Client newClient = new Client(ctr.getPlayerNick(), client.getSocket(), ctr.getCardAmount());
					table.getAwaitingPlayers().add(newClient);
					table.getIncomingPlayers().remove(client);
					
					String[] param = new String[1]; param[0] = "OK Accepted new player "+ctr.getPlayerNick();
					try {
						Request r = new OKRequestFactory().build(param, new NullRequestHandler());
						r.send(new PrintWriter(socket.getOutputStream()));
					} catch (Exception e){}
					
					param = new String[1]; param[0] = "OK Joined table at port "+table.getPort();
					try {
						Request r = new OKRequestFactory().build(param, new NullRequestHandler());
						r.send(new PrintWriter(newClient.getSocket().getOutputStream()));
					} catch (Exception e){}
				}
			}
		}
	}
}
